package edu.liu.db;

import java.sql.*;
import java.io.*;
import java.util.*;

public class DBQueryEngine
{
	String driver;
	String jdbcURL;
	String userName;
	String password;
		
	public DBQueryEngine(String driver,String jdbcURL)
	{
		this.driver=driver;
		this.jdbcURL=jdbcURL;
		userName="";
		password="";
		
	}
	
	public DBQueryEngine(String driver,String jdbcURL, String userName,String password)
	{
		this.driver=driver;
		this.jdbcURL=jdbcURL;
		this.userName=userName;
		this.password=password;
	}
	
	
	public DisconnectedResultSet executeQuery(String sql) throws Exception
	{
		Class.forName(driver).newInstance();
		Connection con=DriverManager.getConnection(jdbcURL,userName,password);
		Statement st=con.createStatement();
		ResultSet rs=st.executeQuery(sql);
		ResultSetMetaData rsm=rs.getMetaData();
		
		int cols=rsm.getColumnCount();
		Vector v=new Vector();
		
		while(rs.next())
		{
			String[] row=new String[cols];
			for(int i=0;i<cols;i++)
			{
				row[i]=rs.getString(i+1);
			}
			v.add(row);
		}
		
		int rows=v.size();
		
		System.out.println("Rows:"+rows);
		
		DisconnectedResultSet  drs=new DisconnectedResultSet(rows,cols);
		
		for(int i=0;i<rows;i++)
		{
			String[] row=(String[])v.get(i);
			for(int j=0;j<cols;j++)
			{
				drs.setData(row[j], i, j);
			}
				
		}
		
		for(int i=0;i<cols;i++)
		{
			drs.setColumnName(rsm.getColumnName(i+1), i);
		}
		
		rs.close();
		con.close();
		
		return drs;
	}
	
}
